// 路由权限
import { RouteLocationNormalized } from 'vue-router'
import store from '@/store';
import router from '@/router';
import NProgress from './progress'

// 路由白名单
export const whiteList: string[] | undefined = [
  '/login', 
  '/auth-redirect',
]

router.beforeEach(async (to: RouteLocationNormalized, from: RouteLocationNormalized, next: any) => {
  NProgress.start()
  if (store.getters.token) {
      if (to.path == '/login') {
          next('/')
          NProgress.done()
      } else {
          if (store.getters.roles.length === 0) {
              try {
                await store.dispatch('user/ACTION_USER_INFO')
                const roles = store.getters.roles // 角色权限数组
                await store.dispatch('permission/ACTION_GENERATE_ROUTER', roles)
                // 动态生成路由
                store.getters.routes.forEach(
                  (route: any) => {
                    router.addRoute(route)
                  }
                )
                next({ ...to, replace: true }) // 页面刷新后仍为此页面
              } catch (error) {
                await store.dispatch('user/ACTION_RESET_TOKEN')
                next(`/login?redirect=${to.path}`)
                NProgress.done()
              }
          } else {
              next()
          }
      }
  } else {
      if (whiteList.indexOf(to.path) !== -1) {
          next()
      } else {
          next(`/login?redirect=${to.path}`)
          NProgress.done()
      }
  }
})

router.afterEach((to: RouteLocationNormalized) => {
  NProgress.done();
  // set page title
  (document as any).title = to.meta.title
})
